import {WechatPlugin} from 'vux'

export default {
  install(Vue) {
    // 判断是否是在微信环境中
    Vue.prototype.$is_weixin = function () {
      var ua = navigator.userAgent.toLowerCase();
      if (ua.match(/MicroMessenger/i) == "micromessenger") {
        return true;
      } else {
        return false;
      }
    }
    Vue.use(WechatPlugin) //微信jssdk
    let wx_url = window.location.href;
    Vue.prototype.$register = function (jsApiList) {
      return new Promise(function (resolve, reject) {
        if (Vue.prototype.$is_weixin()) {
          Vue.prototype.$http.get("/wechat/auth/jsapiSignature?url=" + ((/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) ? wx_url : window.location.href)).then(res => {
            // alert("签名获取成功")
            let data = res.data.data;
            data['jsApiList'] = jsApiList
            //配置
            Vue.prototype.$wechat.config(data)
            Vue.prototype.$wechat.ready(() => {
              resolve()
            })
            Vue.prototype.$wechat.error(function (res) {
              alert(JSON.stringify(res))
              reject("注册服务错误！", res)
            });
          }).catch(res => {
            reject("获取签名错误！", res)
          })
        } else {
          reject("不在微信环境之中")
        }

      })
    }
  }
}
